package net.bwie.realtime.jtp.dim.function;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

public class DimHbaseSinkFunction extends RichSinkFunction<String> {

    /**
     * 定义变量：数据库连接
     */
    private Connection connection = null;



    @Override
    public void open(Configuration parameters) throws Exception {
// s1-创建配置对象，设置属性值，比如连接ZK集群信息
        org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create();
        conf.set(HConstants.CLIENT_ZOOKEEPER_QUORUM, "node101,node102,node103");
        conf.set(HConstants.CLIENT_ZOOKEEPER_CLIENT_PORT, "2181");
// s2-实例化Connection连接
        connection = ConnectionFactory.createConnection(conf);
    }

    @Override
    public void invoke(String value, Context context) throws Exception {
/*
          {
              "operate_type": "insert",
              "db_name": "jtp_mall",
              "operate_data": {
                  "dic_code": "1305",
                  "create_time": "2025-01-11 11:30:49.0",
                  "parent_code": "13",
                  "dic_name": "拍错",
                  "operate_time": "2025-01-11 11:30:49.0"
              },
              "table_name": "base_dic",
              "family_name": "info",
              "ts_ms": 1737688970209,
              "row_key_column": "dic_code",
              "hbase_table_name": "dim_base_dic"
          }
        */

        JSONObject jsonObject = JSON.parseObject(value);
        String tableName = jsonObject.getString("hbase_table_name");
        String familyName = jsonObject.getString("family_name");
        String rowKeyColumn = jsonObject.getString("row_key_column");
        String operateType = jsonObject.getString("operate_type");
        JSONObject dataObject = jsonObject.getJSONObject("operate_data");
        // s3-创建表，如果表不存在时: create 't1', 'f1'
        createHbaseTable(tableName, familyName);
        // s4-实例化Table对象
        Table table = connection.getTable(TableName.valueOf(tableName));
        // s5-1插入数据：put ‘dim_base_dic’, ’1305‘, 'info:dic_name', '拍错'
        if("insert".equals(operateType) || "update".equals(operateType)){
            // 依据表的主键字段名称获取对应值
            String rowKeyValue = dataObject.getString(rowKeyColumn);
            Put put = new Put(Bytes.toBytes(rowKeyValue));
            // 添加列
            for (String columnName : dataObject.keySet()) {
                String columnValue = dataObject.getString(columnName);
                // 当列值不为null时，插入hbase表
                if(null != columnValue){
                    put.addColumn(
                            Bytes.toBytes(familyName), Bytes.toBytes(columnName) , Bytes.toBytes(columnValue)
                    );
                }
            }
            table.put(put);
        }
        // s5-2删除数据：delete ‘dim_base_dic’, ’1305‘
        else if("delete".equals(operateType)){
            // 依据表的主键字段名称获取对应值
            String rowKeyValue = dataObject.getString(rowKeyColumn);
            Delete delete = new Delete(Bytes.toBytes(rowKeyValue));
            table.delete(delete);
        } else {
            System.out.println("数据异常，非insert、update和delete类型操作，操作数据：" + value);
        }
        // s6-1-关闭
        table.close();

    }

    /**
     * HBase数据库中表不存在时，依据表名称和列簇名称创建表
     *
     * @param table  表名称
     * @param family 列簇名称
     */
    private void createHbaseTable(String table, String family) throws Exception {
        // a-管理对象
        Admin admin = connection.getAdmin();
        // b-表不存在时，创建表
        TableName tableName = TableName.valueOf(table);
        if (!admin.tableExists(tableName)) {
        // 表描述符-构造器
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);
            // 列簇描述符-构造器
            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder
                    .newBuilder(Bytes.toBytes(family));
            // 表添加列簇
            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());
            // 创建表
            admin.createTable(tableDescriptorBuilder.build());
        }
        // c-关闭
        admin.close();
    }

    @Override
    public void close() throws Exception {
        super.close();
    }


}